package com.manli.api.service;

import com.manli.api.pojo.*;
import com.manli.api.util.SessionInfoUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;

import com.manli.api.util.ResultUtil;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.manli.api.dao.ViewOrderGoodsDao;
import com.manli.api.dto.ViewOrderGoods;

import javax.servlet.http.HttpServletRequest;


@Service("viewOrderGoodsService")
public class ViewOrderGoodsService {
    @Autowired
    ViewOrderGoodsDao viewOrderGoodsDao;
    @Autowired
    SQLManager sqlManager;
    @Autowired
    SessionInfoUtils sessionInfoUtils;


    /**
     * 商户交易记录
     * 复制于个人中心我的订单列表信息
     * @param orderGoods
     * @param request
     * @return
     */
    public Result getMineBranchOrderInfo(QueryViewOrderGoods orderGoods, HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);

        String paramStr = "";
        if(sessionInfo.getBranchId().intValue() != 1){
            paramStr += " and branch_id = " + sessionInfo.getBranchId() ;
            if(sessionInfo.getPartnerId() != null){
                paramStr += " and partner_id = " + sessionInfo.getPartnerId() ;
            }else{
                paramStr += " and partner_id is null " ;
            }
        }
        if(orderGoods.getBranchId() != null){
            paramStr += " and branch_id = " + orderGoods.getBranchId() ;
        }
        if(orderGoods.getPartnerId() != null){
            paramStr += " and partner_id = " + orderGoods.getPartnerId() ;
        }
        if(orderGoods.getBuyerPhone() != null){
            paramStr += " and buyer_phone like '%"+orderGoods.getBuyerPhone() +"%' " ;
        }
        if(orderGoods.getBuyerName() != null){
            paramStr += " and buyer_name like '%"+orderGoods.getBuyerName() +"%' " ;
        }
        if(orderGoods.getBuyMethod() !=null){
            paramStr += " and buy_method = " + orderGoods.getBuyMethod() ;
        }
        if(orderGoods.getGoodsName() != null){
            paramStr += " and goods_name like '%"+orderGoods.getGoodsName() +"%' " ;
        }
        if(orderGoods.getGoodsModelName() != null){
            paramStr += " and goods_model_name like '%"+orderGoods.getGoodsModelName() +"%' " ;
        }
        if(orderGoods.getOrderNoMain() != null){
            paramStr += " and order_no_main like '%"+orderGoods.getOrderNoMain() +"%' " ;
        }
        if(orderGoods.getOrderNoSub() !=null){
            paramStr += " and order_no_sub like '%"+orderGoods.getOrderNoSub() +"%' " ;
        }
        if(orderGoods.getCreateTimeStart() != null){
            paramStr += " and create_time >= '"+orderGoods.getCreateTimeStart() +"' "  ;
        }
        if(orderGoods.getCreateTimeEnd() != null){
            paramStr += " and create_time <= '"+orderGoods.getCreateTimeEnd()+"' "  ;
        }
        if(orderGoods.getStatus() != null){
            paramStr += " and status = " + orderGoods.getStatus() +" ";
        }
        //获取指定数量的主订单号
        List<ViewOrderGoods> limitLists =  sqlManager.execute(new SQLReady(
                "select * from view_order_goods " +
                        "where 1=1 " +
                        paramStr +
                        " group by order_no_main   " +
                        "order by create_time desc " +
                        "limit ? , ? ",
                (orderGoods.getPage()-1)*orderGoods.getLimit() ,
                orderGoods.getLimit()),ViewOrderGoods.class);
        String sqlOrderNoMainStr = "" ;
        for(ViewOrderGoods viewOrderGood : limitLists){
            sqlOrderNoMainStr+=viewOrderGood.getOrderNoMain()+",";
        }
        if(sqlOrderNoMainStr.length() == 0 ){
            return ResultUtil.success(null);
        }
        sqlOrderNoMainStr = sqlOrderNoMainStr.substring(0,sqlOrderNoMainStr.length()-1);
        //获取数量
        List<ViewOrderGoods> countList = sqlManager.execute(
                new SQLReady("select * from view_order_goods " +
                        "where 1=1 " +
                        paramStr +
                        " group by order_no_main  " ),ViewOrderGoods.class);
        //获取列表
        List<ViewOrderGoods> viewOrderGoodsList = sqlManager.execute(new SQLReady(
                "select * from view_order_goods " +
                        "where 1=1 " +
                        paramStr +
                        " and find_in_set(order_no_main, ? ) > 0 " +
                        "order by create_time desc " ,
                sqlOrderNoMainStr) ,ViewOrderGoods.class);

        Map<String,List<ViewOrderGoods>> ret =
                viewOrderGoodsList
                        .stream()
                        .collect(Collectors.groupingBy(e -> fetchGroupKeyForGetMineOrderInfo(e), LinkedHashMap::new,Collectors.toList()));
        //倒序
        List<List<ViewOrderGoods>> retList = new ArrayList<>();
        for (Map.Entry<String, List<ViewOrderGoods>> entry : ret.entrySet()) {
            retList.add(entry.getValue());
        }
        return ResultUtil.success(retList,Long.valueOf(countList.size()));
    }
    //我的订单分组
    private String fetchGroupKeyForGetMineOrderInfo(ViewOrderGoods viewOrderGoods){
        return viewOrderGoods.getOrderNoMain() ;
    }


    public Result orderRefuseInfo(QueryViewOrderGoods orderGoods, HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        LambdaQuery<ViewOrderGoods> viewOrderGoodsLambdaQuery = viewOrderGoodsDao.createLambdaQuery();
        if(sessionInfo.getBranchId().intValue() != 1){
            viewOrderGoodsLambdaQuery.andEq("branch_id",sessionInfo.getBranchId());
            if(sessionInfo.getPartnerId() != null){
                viewOrderGoodsLambdaQuery.andEq("partner_id" , sessionInfo.getPartnerId());
            }else{
                viewOrderGoodsLambdaQuery.andIsNull("partner_id");
            }
        }
        if(orderGoods.getStatus()!=null){
            viewOrderGoodsLambdaQuery.andEq("status",orderGoods.getStatus());
        }else{
            List status = new ArrayList();;
            status.add(2);
            status.add(3);
            viewOrderGoodsLambdaQuery.andIn("status",status);
        }
        if(orderGoods.getBranchId() != null){
            viewOrderGoodsLambdaQuery.andEq("branch_id",orderGoods.getBranchId());
        }
        if(orderGoods.getPartnerId() != null){
            viewOrderGoodsLambdaQuery.andEq("partner_id" , orderGoods.getPartnerId());
        }
        if(orderGoods.getBuyerPhone() != null){
            viewOrderGoodsLambdaQuery.andLike("buyer_phone" , orderGoods.getBuyerPhone());
        }
        if(orderGoods.getBuyerName() != null){
            viewOrderGoodsLambdaQuery.andLike("buyer_name",orderGoods.getBuyerName());
        }
        if(orderGoods.getBuyMethod() !=null){
            viewOrderGoodsLambdaQuery.andEq("buy_method",orderGoods.getBuyMethod());
        }
        if(orderGoods.getGoodsName() != null){
            viewOrderGoodsLambdaQuery.andLike("goods_name",orderGoods.getGoodsName());
        }
        if(orderGoods.getGoodsModelName() != null){
            viewOrderGoodsLambdaQuery.andLike("goods_model_name" , orderGoods.getGoodsModelName());
        }
        if(orderGoods.getOrderNoMain() != null){
            viewOrderGoodsLambdaQuery.andLike("order_no_main" , orderGoods.getOrderNoMain());
        }
        if(orderGoods.getOrderNoSub() !=null){
            viewOrderGoodsLambdaQuery.andLike("order_no_sub" , orderGoods.getOrderNoSub());
        }
        if(orderGoods.getCreateTimeStart() != null){
            viewOrderGoodsLambdaQuery.andGreatEq("create_time",orderGoods.getCreateTimeStart());
        }
        if(orderGoods.getCreateTimeEnd() != null){
            viewOrderGoodsLambdaQuery.andLessEq("create_time",orderGoods.getCreateTimeEnd());
        }
        long count = viewOrderGoodsLambdaQuery.count();
        List<ViewOrderGoods> retList = viewOrderGoodsLambdaQuery.desc("create_time").
                limit(orderGoods.getPage(),orderGoods.getLimit()).select();
        return ResultUtil.success(retList,count);
    }
}
